package gui;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.JFrame;

import Aplicacion.MP3Player;
import Aplicacion.Variables_globales;
import Entidades.Paises;
import Entidades.Posesion;

import javax.swing.JPanel;
import java.awt.BorderLayout;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;
import javax.swing.SwingConstants;
import javax.swing.Timer;

import java.awt.Font;
import java.util.LinkedList;
import java.util.Random;
import java.awt.GridLayout;
import javax.swing.JComboBox;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

import data.Database;

import java.awt.Dimension;

public class AtacarGUI implements WindowListener, ActionListener, ChangeListener {
	private final Database db = new Database();
	private final Random rand = new Random();
	private Timer anim = null;
	private final String[] dice = {
		"/Imagenes/Dice/Dice1.png",
		"/Imagenes/Dice/Dice2.png",
		"/Imagenes/Dice/Dice3.png",
		"/Imagenes/Dice/Dice4.png",
		"/Imagenes/Dice/Dice5.png",
		"/Imagenes/Dice/Dice6.png"
	};
	
	private int soldados;
	private LinkedList<Paises> paises;
	private LinkedList<Integer> colindantes;
	
	private long initTime;
	private long endTime;
	private int jugador1;
	private int jugador2;
	
	private int id_pais_ganador;
	private int id_pais_perdedor;
	
	private JFrame frame;
	private JLabel Dice1;
	private JLabel Dice2;
	private JLabel Pais1;
	private JComboBox listaPaises;
	private JButton btnAtacar;
	private JSpinner choseSoldados;
	
	public AtacarGUI(int id_pais, String nombre, int x, int y) {
		id_pais_perdedor = id_pais;
		this.initialize();
		
		frame.setLocation(x, y);
		Pais1.setText(nombre);
		
		paises = db.getPaises();
		colindantes = db.getColindantes(id_pais);
		if (colindantes.size() <= 0) {
			listaPaises.setEnabled(false);
			btnAtacar.setEnabled(false);
		} else {
			for (Integer id: colindantes) {
				for (Paises p: paises){
					if (p.getIdPais() == id) {
						for (Posesion pos: db.getPosesion()) {
							if (pos.getIDPais() == id && pos.getSoldados() > 1) {
								listaPaises.addItem(p.getNombre());
							}
						}
					}
				}
			}
			if (listaPaises.getModel().getSize() <= 0) {
				listaPaises.setEnabled(false);
				btnAtacar.setEnabled(false);
			}
		}
		
		frame.setVisible(true);
	}

	private void initialize() {
		frame = new JFrame();
		frame.setTitle("Atacar");
		frame.setAlwaysOnTop(true);
		frame.setResizable(false);
		frame.setSize(237, 283);
		frame.addWindowListener(this);
		frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		
		JPanel panel_1 = new JPanel();
		frame.getContentPane().add(panel_1, BorderLayout.SOUTH);
		panel_1.setLayout(new GridLayout(0, 1, 0, 0));
		
		JPanel panel = new JPanel();
		panel_1.add(panel);
		
		Pais1 = new JLabel("Pais 1");
		Pais1.setHorizontalAlignment(SwingConstants.CENTER);
		Pais1.setPreferredSize(new Dimension(200, 30));
		panel.add(Pais1);
		Pais1.setFont(new Font("Lucida Grande", Font.BOLD, 18));
		
		JPanel panel_4 = new JPanel();
		panel_1.add(panel_4);
		
		btnAtacar = new JButton("Atacar Desde");
		btnAtacar.setPreferredSize(new Dimension(200, 29));
		btnAtacar.addActionListener(this);
		panel_4.add(btnAtacar);
		
		JPanel panel_5 = new JPanel();
		panel_1.add(panel_5);
		
		listaPaises = new JComboBox();
		listaPaises.setPreferredSize(new Dimension(200, 27));
		panel_5.add(listaPaises);
		listaPaises.setFont(new Font("Lucida Grande", Font.ITALIC, 13));
		
		JPanel panel_6 = new JPanel();
		panel_1.add(panel_6);
		
		JLabel lvlMov = new JLabel("Mover ");
		lvlMov.setHorizontalAlignment(SwingConstants.CENTER);
		panel_6.add(lvlMov);
		
		choseSoldados = new JSpinner();
		choseSoldados.setPreferredSize(new Dimension(100, 30));
		choseSoldados.setEnabled(false);
		choseSoldados.addChangeListener(this);
		panel_6.add(choseSoldados);
		
		JLabel lvlMov2 = new JLabel("Soldados");
		lvlMov2.setHorizontalAlignment(SwingConstants.CENTER);
		panel_6.add(lvlMov2);
		
		JPanel panel_2 = new JPanel();
		frame.getContentPane().add(panel_2, BorderLayout.WEST);
		
		Dice1 = new JLabel("");
		Dice1.setIcon(new ImageIcon(AtacarGUI.class.getResource("/Imagenes/Dice/Dice3.png")));
		panel_2.add(Dice1);
		
		JPanel panel_3 = new JPanel();
		frame.getContentPane().add(panel_3, BorderLayout.EAST);
		
		Dice2 = new JLabel("");
		Dice2.setIcon(new ImageIcon(AtacarGUI.class.getResource("/Imagenes/Dice/Dice5.png")));
		panel_3.add(Dice2);
		
		JLabel lblVs = new JLabel("Vs");
		lblVs.setFont(new Font("Lucida Grande", Font.BOLD, 16));
		lblVs.setHorizontalAlignment(SwingConstants.CENTER);
		frame.getContentPane().add(lblVs, BorderLayout.CENTER);
		
		listaPaises.addActionListener(this);
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == btnAtacar) {
			if (anim != null) {
				anim = null;
			}
			initTime = System.currentTimeMillis();
//			Variables_globales.DADOS.start();
			
			try {
				MP3Player MP32 = new MP3Player();
				MP32.playDaemon(this.getClass().getResource("/Imagenes/dados.mp3").toString());
			} catch (IllegalThreadStateException ex) {}
			
			anim = new Timer(300, new tirarDados());
			anim.start();
		}
		
		if (e.getSource() == listaPaises) {
			paises = db.getPaises();
			for (Paises p: paises) {
				if (p.getNombre().equalsIgnoreCase(listaPaises.getSelectedItem().toString())) {
					for (Posesion pos: db.getPosesion()) {
						if (pos.getIDPais() == p.getIdPais() && pos.getSoldados() > 1) {
							try {
								choseSoldados.setModel(new SpinnerNumberModel(1, 1, (db.getSoldadosDisponiblesEnPais(p.getIdPais())-1), 1));
							} catch (IllegalArgumentException ex) {
								frame.dispose();
							}
							soldados = db.getSoldadosDisponiblesEnPais(p.getIdPais());
							id_pais_ganador = p.getIdPais();
						}
					}
				}
			}
		}
	}
	
	@Override
	public void stateChanged(ChangeEvent e) {
		if (e.getSource() == choseSoldados) {
			int tmp = Integer.parseInt(choseSoldados.getValue().toString());
			db.ganar(id_pais_ganador, id_pais_perdedor, tmp, (soldados-tmp));
			
			try {
				MP3Player WAV = new MP3Player();
				WAV.playDaemon(this.getClass().getResource("/Imagenes/clickMenu.mp3").toString());
			} catch (IllegalThreadStateException ex) {}
		}
	}
	
	public class tirarDados implements ActionListener {
		@Override
		public void actionPerformed(ActionEvent arg0) {
			jugador1 = rand.nextInt(5);
			jugador2 = rand.nextInt(5);
			
			Dice1.setIcon(new ImageIcon(AtacarGUI.class.getResource(dice[jugador1])));
			Dice2.setIcon(new ImageIcon(AtacarGUI.class.getResource(dice[jugador2])));
			
			endTime = System.currentTimeMillis();
			if ((endTime-initTime) >= 4500) {
				btnAtacar.setEnabled(false);
				
				if (jugador1 > jugador2) {
					JOptionPane.showMessageDialog(frame, "Has Ganado");
					choseSoldados.setEnabled(true);
					db.ganar(id_pais_ganador, id_pais_perdedor, 1, (soldados-1));
				} else {
					JOptionPane.showMessageDialog(frame, "Has Perdido");
					db.updateSoldadosPais(
							id_pais_ganador, 
							(soldados-((soldados <= 4)?rand.nextInt(3):rand.nextInt((db.getSoldadosDisponiblesEnPais(id_pais_ganador)-1))))
					);
					
					if (soldados > 1) {
						btnAtacar.setEnabled(true);
					}
				}
				anim.stop();
			}
		}
	}
	
	@Override
	public void windowClosing(WindowEvent e) {
		Variables_globales.PAUSA = false;
	}
	
	@Override
	public void windowActivated(WindowEvent e) {}

	@Override
	public void windowClosed(WindowEvent e) {}

	@Override
	public void windowDeactivated(WindowEvent e) {}

	@Override
	public void windowDeiconified(WindowEvent e) {}

	@Override
	public void windowIconified(WindowEvent e) {}

	@Override
	public void windowOpened(WindowEvent e) {}
}